package com.wu.client.utils;

import io.minio.*;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Cousin
 * @date 2024/10/15
 * @Description
 */
@Component
@RequiredArgsConstructor
public class MinIoUtil {

    private static final Logger log = LoggerFactory.getLogger(MinIoUtil.class);
    private final MinioClient minioClient;

    // 创建存储桶
    private void createBucket(String bucketName) throws Exception {
        // 检查存储桶是否存在
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!isExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    // 上传文件
    public void uploadFile(String bucketName, String objectName, InputStream fileStream, long size) throws Exception {
        if (bucketExists(bucketName)) {
            createBucket(bucketName);
        }
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(fileStream, size, -1)
                        .build());
        log.info("{}已上传到{}桶", objectName, bucketName);
    }

    // 下载文件
    public InputStream downloadFile(String bucketName, String objectName) throws Exception {
        if (bucketExists(bucketName)) {
            log.error("{}桶不存在", bucketName);
            return null;
        }
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    // 删除文件
    public void deleteFile(String bucketName, String objectName) throws Exception {
        if (bucketExists(bucketName)) {
            log.error("{}桶不存在", bucketName);
            return;
        }
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
        log.info("{}已从{}桶中删除", objectName, bucketName);
    }

    // 列出存储桶中的所有对象
    private List<String> listObjects(String bucketName) {
        List<String> objectNames = new ArrayList<>();
        // 使用 listObjects 方法获取对象列表
        minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build()).forEach(item -> {
            try {
                objectNames.add(item.get().objectName());
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        });
        return objectNames;
    }

    // 检查存储桶是否存在
    private boolean bucketExists(String bucketName) throws Exception {
        return !minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    // 获取文件访问url
    public String getFileUrlWithTime(String bucketName, String objectName, int duration, TimeUnit timeUnit) {
        try {
            // 根据文件扩展名获取 MIME 类型
            String contentType = URLConnection.guessContentTypeFromName(objectName);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            Map<String, String> reqParams = new HashMap<>();
            // 设置为 inline 模式预览
            reqParams.put("response-content-disposition", "inline");
            // 设置内容类型
            reqParams.put("response-content-type", contentType);
            GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder().method(Method.GET)
                    .bucket(bucketName).extraQueryParams(reqParams)
                    .object(objectName).expiry(duration, timeUnit).build();
            return minioClient.getPresignedObjectUrl(build);
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }
    }

    public String getFileUrlDefault(String bucketName, String objectName) {
        try {
            // 根据文件扩展名获取 MIME 类型
            String contentType = URLConnection.guessContentTypeFromName(objectName);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            Map<String, String> reqParams = new HashMap<>();
            // 设置为 inline 模式预览
            reqParams.put("response-content-disposition", "inline");
            // 设置内容类型
            reqParams.put("response-content-type", contentType);
            GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder().method(Method.GET)
                    .bucket(bucketName).extraQueryParams(reqParams)
                    .object(objectName).expiry(65, TimeUnit.MINUTES).build();
            return minioClient.getPresignedObjectUrl(build);
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }
    }
    // 判断文件是否存在的方法
    public boolean doesFileExist(String bucketName, String objectName) {
        try {
            minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return true;
        } catch (Exception e) {
            log.error("在{}桶中不存在{}",bucketName,objectName);
            return false;
        }
    }
}